#encoding=utf8
'''
Created on 2012-10-11

@author: Administrator
'''
from DbOperator import DbOperator
from Messages import Messages
from pub import Func
from pub.Config import Config
class MessagesModel(DbOperator):
    '''
    信息操作模型
    '''


    def __init__(self):
        '''
        Constructor
        '''
        DbOperator.__init__(self)
    def addNewMessage(self,oMessage):
        """
        增加一条新信息到信息库
        @param oMessage:Messages
        @return: int 
        """
        if(oMessage):
            values = (
                      Messages.MSGTITLE,oMessage.get_title(),
                      Messages.CREATED,oMessage.get_created(),
                      Messages.MSGCONTENT,oMessage.get_content(),
                      Messages.MSGSENDED,Config.I_SYS_ZERO,
                      Messages.MSGSENDER,oMessage.get_msg_sender(),
                      Messages.MSGRECIEVER,oMessage.get_msg_reciever(),
                      Messages.MSGSTATE,oMessage.get_msg_state(),
                      Messages.MSGTYPE,oMessage.get_msgtype(),
                      )
            aParam={Config.S_TABLE:Messages.TABLE_NAME,
                    Config.S_SEARCHFIELDS:"`%s`='%s',`%s`='%s',`%s`='%s',`%s`='%s',`%s`='%s',`%s`=%s,`%s`=%s,`%s`=%s "%values,
            }
            return (self.doInsert(aParam),Config.I_MESSAGE_ADD_OK)
            
    def delMessageById(self,MessageId):
        """
        根据信息编号删除一条信息
        """
        aParam = {
                   Config.S_TABLE:Messages.TABLE_NAME,
                   Config.S_SEARCHCONDITION:" `%s`=%s  " %  (Messages.PRIMARY_KEY,MessageId),
         }
        return self.doDelete(aParam)
    def getMessageList(self,MsgType,MsgRecieverId,MsgSended,StartPosition=None,Count=None):
        """
        取得消息列表
        @param MsgType:int    获取的消息类型 0 系统消息 1 用户消息
        @param MsgRecieverId:int 接收的用户Id
        @param MsgSended: 消息是否已发送
        @param StartPosition:integer
        @param Count: integer
        @return:List 
        """
#        Sql = "SELECT * from message where (msgReciever=UserId and hassend=0 and MsgSender<>0) or (UserId in (msgReciever) and MsgSender=0  ) "
#        Sql = " update message set msgReciever=REPLACE(msgReciever,old,new)")
        searchCondition = (
                            Messages.MSGRECIEVER, MsgRecieverId,
                            Messages.MSGSENDED,Config.I_SYS_ZERO,
                            Messages.MSGSENDER,Config.I_SYS_ZERO,
                            Messages.MSGRECIEVER,",%s,"%(MsgRecieverId),
                            Messages.MSGSENDER,Config.I_SYS_ZERO,
                           )
        sHas_Join = "LEFT JOIN %s on %s=%s"
        aParam = {
              Config.S_TABLE:Messages.TABLE_NAME,
              Config.S_SEARCHFIELDS:"sq_message.*,sq_userinfo.UserNickName ",
              Config.HAS_JOIN:sHas_Join%('sq_userinfo','sq_message.MsgSender','sq_userinfo.Id'),
#              Config.S_SEARCHCONDITION:" `%s` =%s AND `%s`=%s AND `%s`=%s AND `%s`=%s " % searchCondition,
              Config.S_SEARCHCONDITION:"(`%s`=%s AND `%s`=%s AND `%s`<>%s) OR ( INSTR(`%s`,'%s')>0 AND `%s`=%s) " % searchCondition,
              Config.S_RESULTROW:1000,
              Config.S_FETCH_ALL:True,   #是否要取出全部信息，为否则须带入limit

        }
        if( StartPosition and (Count>0)):
            aParam[Config.S_FETCH_ALL]=False
            aParam[Config.S_LIMIT]="%s,%s"%(StartPosition,Count)
        return self.getFieldByCondition(aParam)
    
if __name__=="__main__":
    oMsg = Messages()
    oMsg.set_title(u"系统即将上线了哦")
    oMsg.set_msg_sender(0)
    oMsg.set_created(Func.getNow())
    oMsg.set_content("热烈欢迎系统要上线了哦")
    oMsg.set_msg_reciever(0)
    oMsg.set_msg_state(0)
    oMsg.set_msg_sended(0)
    oMsg.set_msgtype(0)
    mMsg = MessagesModel()
#    print mMsg.addNewMessage(oMsg)
    dMsgList = mMsg.getMessageList(0, 4, 0, 0, 10)
#    print n
    tmp={}
    if dMsgList!=None:
        sStr = ""
        for msg in dMsgList:
#            tmp[msg["Id"]]["title"]=msg["title"]
#            tmp[msg["Id"]]["infoType"]=msg["Msgtype"]
            print msg
            if msg["Msgtype"]==2:#如果是好友邀请消息，则分割Content ^
                sTmp = msg["Content"].split("^")
                print sTmp
                msg["requestFlag"] = sTmp[0]
                msg["keywords"] = sTmp[1]
                msg["roomTitle"] = sTmp[2]
                msg["infos"] = sTmp[3]
            elif msg["Msgtype"]==1:
                msg["requestFlag"] = 0
                msg["keywords"] = 0
                msg["roomTitle"] = 0
                msg["infos"] = msg["Content"]
            if msg["MsgSender"]==0:
                msg["UserNickName"]="系统用户"
            data = (msg["Titile"],
                    msg["Msgtype"],
                    msg["Created"],
                    msg["MsgSender"],
                    msg["UserNickName"],
                    msg["requestFlag"],
                    msg["keywords"],
                    msg["roomTitle"],
                    msg["infos"],
            )
            sStr = sStr+"%s#%s#%s#%s#%s#%s#%s#%s#%s#"%data
    print sStr    
     